const api = require('../../../../ws_micro_shop/utils/api.js');
const app = getApp();

let is_no_more = false;
let is_loading = false;
let p = 2;
let timer = null;
let countDown = null;

Page({
  data: {
    status: -1,
    order_list: [],
    show_no_data_tip: false,
    hide: 1,
    qrcode: '',
    leave_time: [],
    theme: app.themeData,
    showpaytypes: false,
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-19.png',
      text: '还没有相关秒杀订单哦~',
    },
    unit: '',
    currVal: '',
    isEmpty: true,
    keywords: '',
  },
  onLoad(options) {
    let _this = this;
    let opts = options || {};
    app.pageOnLoad(this);
    app.loadCurrencyUnit().then(res => {
      _this.setData({
        unit: res.unit,
      });
    });
    is_no_more = false;
    is_loading = false;
    p = 2;
    let pages = getCurrentPages();
    if (pages.length < 2) {
      _this.setData({
        show_index: true,
      });
    }
    this.setData({
      commentSwitch: wx.getStorageSync('store').comment_switch,
      opts,
      status: opts.status || -1,
    });
  },
  onShow() {
    this.loadOrderList(this.data.status);
  },
  onHide() {
    timer && clearInterval(timer);
    countDown && clearInterval(countDown);
  },
  onUnload() {
    timer && clearInterval(timer);
    countDown && clearInterval(countDown);
  },
  switchList(e) {
    let data = e.currentTarget.dataset;
    is_no_more = false;
    is_loading = false;
    p = 2;
    this.loadOrderList(data.status);
  },
  loadOrderList(sts, k = '') {
    countDown && clearInterval(countDown);
    let status = sts;
    !status && (status = -1);
    let _this = this;
    _this.setData({
      status,
    });
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.miaosha.order_list,
      data: {
        status,
        keywords: k,
      },
      success: function (res) {
        if (res.code === 0) {
          let leave_time = {};
          for (let i = 0; i < res.data.list.length; i++) {
            let leaveTime = Number(res.data.list[i].leave_time);
            leave_time[res.data.list[i].order_no] = leaveTime >= 0 ? leaveTime : 0;
          }
          _this.setData({
            order_list: res.data.list,
            leave_time,
          });
          countDown = setInterval(function () {
            for (let x in _this.data.leave_time) {
              if (_this.data.leave_time[x] <= 0) {
                _this.data.leave_time[x] = 0;
              } else {
                _this.data.leave_time[x]--;
              }
            }
            _this.setData({
              leave_time: _this.data.leave_time,
            });
          }, 1000);
        }
        _this.setData({
          show_no_data_tip: (_this.data.order_list.length === 0),
        });
      },
      complete: function () {
        wx.hideLoading();
      },
    });
  },
  onReachBottom() {
    let _this = this;
    if (is_loading || is_no_more) {
      return;
    }
    is_loading = true;
    app.ws_micro_shoprequest({
      url: api.miaosha.order_list,
      data: {
        status: _this.data.status,
        page: p,
        keywords: _this.data.keywords,
      },
      success: function (res) {
        if (res.code === 0) {
          let order_list = _this.data.order_list.concat(res.data.list);
          _this.setData({
            order_list,
          });
          if (res.data.list.length === 0) {
            is_no_more = true;
          }
        }
        p++;
      },
      complete: function () {
        is_loading = false;
      },
    });
  },
  showPayType(e) {
    let index = e.currentTarget.dataset.index;
    let order_list = this.data.order_list;
    let order = order_list[index];
    let pay_type_list = order.pay_type_list;
    this.setData({
      showpaytypes: true,
      pay_type_list,
      orderID: e.currentTarget.dataset.id,
      discountId: e.currentTarget.dataset.discount == 1 ? e.currentTarget.dataset.payment : -1,
    });
  },
  disabledClick() {
    // it`s necessary
  },
  hidePayType() {
    this.setData({
      showpaytypes: false,
    });
  },
  orderPay(e) {
    let that = this;
    app.getSubscribeMessage(0).then(response => {
    let payment = Number(e.currentTarget.dataset.payment);
      let id = that.data.orderID;
    wx.showLoading({
      title: '正在提交',
      mask: true,
    });
      that.setData({
      showpaytypes: false,
    });
    if (payment === 0) {
        that.WechatPay(id);
    } else if (payment === 3) {
        that.setData({
        showpaytypes: false,
      });
        that.BalancePay(id);
    } else if (payment === 5) {
      if (wx.getStorageSync('user_info').unionid && wx.getStorageSync('user_info').card) {
          that.CardPay(id);
      } else {
        wx.hideLoading();
        wx.showModal({
          title: '友情提示',
          content: '你还未开通会员卡，是否前往个人中心开通？',
          success: function (res) {
            if (res.confirm) {
              app.util.navigateTo('/ws_micro_shop/pages/user/user', {}, false);
            }
          },
        });
      }
    } else if (payment === 6) {
        that.CheckPay(id);
    }
    })
  },
  WechatPay(order_id) {
    app.ws_micro_shoprequest({
      url: api.miaosha.pay_data,
      data: {
        order_id: order_id,
        pay_type: 'WECHAT_PAY',
      },
      complete: function () {
        wx.hideLoading();
      },
      success: function (res) {
        if (res.code === 0) {
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            complete: function (e) {
              if (e.errMsg === 'requestPayment:fail' || e.errMsg === 'requestPayment:fail cancel') {
                wx.showModal({
                  title: '提示',
                  content: '订单尚未支付',
                  showCancel: false,
                  confirmText: '确认',
                  success: function (res) {
                    if (res.confirm) {
                      wx.redirectTo({
                        url: '/ws_micro_shop_ms/pages/miaosha/order/order?status=0',
                      });
                    }
                  },
                });
                return;
              }
              wx.redirectTo({
                url: '/ws_micro_shop_ms/pages/miaosha/order/order?status=1',
              });
            },
          });
        }
        if (res.code === 1) {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
    });
  },
  BalancePay(order_id) {
    app.ws_micro_shoprequest({
      url: api.miaosha.pay_data,
      data: {
        order_id: order_id,
        pay_type: 'BALANCE_PAY',
      },
      complete: function () {
        wx.hideLoading();
      },
      success: function (res) {
        if (res.code === 0) {
          wx.redirectTo({
            url: '/ws_micro_shop_ms/pages/miaosha/order/order?status=1',
          });
        }
        if (res.code === 1) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },
  CardPay(order_id) {
    app.ws_micro_shoprequest({
      url: api.miaosha.pay_data,
      data: {
        order_id: order_id,
        pay_type: 'CARD_PAY',
      },
      complete: function () {
        wx.hideLoading();
      },
      success: function (res) {
        if (res.code === 0) {
          wx.redirectTo({
            url: '/ws_micro_shop_ms/pages/miaosha/order/order?status=1',
          });
        }
        if (res.code === 1) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },
  CheckPay(order_id){
    app.ws_micro_shoprequest({
      url: api.miaosha.pay_data,
      data: {
        order_id: order_id,
        pay_type: 'CLERK_PAY',
      },
      success: function (res) {
        if (res.code === 0) {
          app.util.navigateTo('/ws_micro_shop_ms/pages/miaosha/order/order', { status: -1 }, true);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
          return;
        }
      },
    });
  },
  orderRevoke(e) {
    let _this = this;
    app.getSubscribeMessage(1).then(response => {
    wx.showModal({
      title: '提示',
      content: '是否取消该订单？',
      cancelText: '否',
      confirmText: '是',
      success: function (res) {
        if (res.cancel) {
          return true;
        }
        if (res.confirm) {
          wx.showLoading({
            title: '操作中',
          });
          app.ws_micro_shoprequest({
            url: api.miaosha.order_revoke,
            data: {
              order_id: e.currentTarget.dataset.id,
            },
            success: function (res) {
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    _this.loadOrderList(_this.data.status);
                  }
                },
              });
            },
          });
        }
      },
    });
    })
  },
  orderConfirm(e) {
    let _this = this;
    wx.showModal({
      title: '提示',
      content: '是否确认已收到货？',
      cancelText: '否',
      confirmText: '是',
      success: function (res) {
        if (res.cancel) {
          return true;
        }
        if (res.confirm) {
          wx.showLoading({
            title: '操作中',
          });
          app.ws_micro_shoprequest({
            url: api.miaosha.confirm,
            data: {
              order_id: e.currentTarget.dataset.id,
            },
            success: function (res) {
              wx.hideLoading();
              wx.showToast({
                title: res.msg,
              });
              if (res.code === 0) {
                _this.loadOrderList(3);
              }
            },
          });
        }
      },
    });
  },
  orderQrcode(e) {
    let _this = this;
    let order_list = _this.data.order_list;
    let index = e.currentTarget.dataset.index;
    let orderId = order_list[index].order_id;
    let orderNo = order_list[index].order_no;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    if (_this.data.order_list[index].offline_qrcode) {
      _this.setData({
        hide: 0,
        qrcode: _this.data.order_list[index].offline_qrcode,
      });
      wx.hideLoading();
    } else {
      app.ws_micro_shoprequest({
        url: api.order.get_qrcode,
        data: {
          order_no: orderNo,
        },
        success: function (res) {
          if (res.code === 0) {
            _this.setData({
              hide: 0,
              qrcode: res.data.url,
            });
            if (timer) {
              timer && clearInterval(timer);
            }
            _this.Loop(orderId);
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
            });
          }
        },
        complete: function () {
          wx.hideLoading();
        },
      });
    }
  },
  hide() {
    timer && clearInterval(timer);
    this.setData({
      hide: 1,
    });
  },
  onNavigate(e) {
    let param = e.currentTarget.dataset;
    let pageUrl = param.url ? param.url : '';
    let urlParams = param.urlParams ? param.urlParams : '';
    let close = param.close ? param.close : '';
    app.util.navigateTo(pageUrl, urlParams, close);
  },
  Loop(id) {
    let _this = this;
    timer = setInterval(function () {
      app.ws_micro_shoprequest({
        url: api.default.orderClerk,
        data: {
          order_id: id,
          type: 'ms',
        },
        success: function (res) {
          if (res.code === 0) {
            if (Number(res.data) === 1) {
              timer && clearInterval(timer);
              _this.setData({
                hide: 1,
              });
              _this.loadOrderList(_this.data.status);
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
            });
          }
        },
      });
    }, 2000);
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
  deleteOrder(e) {
    let that = this;
    let { orderid: order_id, idx } = e.currentTarget.dataset;
    let orderlist = that.data.order_list;
    wx.showModal({
      title: '提示',
      content: '是否要删除该订单',
      success: res => {
        if (res.confirm) {
          app.ws_micro_shoprequest({
            url: api.order.deleteorder,
            data: {
              order_id,
              type: 'ms',
            },
            success: function (res) {
              if (res.code === 0) {
                orderlist.splice(idx, 1);
                that.setData({
                  order_list: orderlist,
                });
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                });
              } else {
                wx.showToast({
                  title: res.msg || '删除失败',
                  icon: 'none',
                });
              }
            },
          });
        }
      },
    });
  },
  inputChange(e) {
    let val = e.detail.value;
    if (val.trim()) {
      this.setData({
        isEmpty: false,
      });
    } else {
      this.setData({
        isEmpty: true,
      });
    }
    this.setData({
      currVal: val,
    });
  },
  clearTxt() {
    let status = this.data.status;
    is_no_more = false;
    is_loading = false;
    p = 2;
    this.setData({
      currVal: '',
      keywords: '',
      order_list: [],
      isEmpty: true,
    });
    this.loadOrderList(status);
  },
  searchTxt(keyword) {
    let keywords = keyword;
    let status = this.data.status;
    is_no_more = false;
    is_loading = false;
    p = 2;
    this.setData({
      keywords,
      order_list: [],
    });
    this.loadOrderList(status, keywords);
  },
  searchSure() {
    let keyword = (this.data.currVal).trim();
    this.searchTxt(keyword);
  },
});
